#!/usr/bin/env python3
import mmap
import optparse
import os.path
import plistlib
import sys
import xml.etree.ElementTree as ET

def getMainDict( queueFile ):
    """
    Check that the queue file contains one and only one dict-entry.
    If this condition is true return the top-level array-element.
    """
    # Convert commas in real-elements to periods.
    tree = ET.parse( queueFile )
    for it in tree.getiterator( "real" ):
        it.text = it.text.replace( ",", "." )

    # Get a property list object for the tree. Return value should 
    # be a list since the main level property is an array of dicts.
    propertyList = plistlib.readPlistFromBytes( bytes( ET.tostring( tree.getroot() ), "utf-8" ) )
    if len( propertyList ) > 1:
        print( ">>>More than one job found in queue. Not going to continue.", file = sys.stderr )
        return None

    # Get the array element.
    return propertyList.pop( 0 )

def main( args ):
    """
    Run the app.
    """
    # Handle options.
    parser = optparse.OptionParser()
    parser.add_option( "-f",
                       "--queue-file",
                       dest = "queue",
                       help = "use FILE as the queue to process",
                       metavar = "FILE" )
    ( options, args ) = parser.parse_args()
    # Sanity checking.
    if options.queue is None:
        print( ">>>Queue file was not specified!", file = sys.stderr )
        parser.parse_args( ["-h"] )
    if not os.path.exists( options.queue ):
        print( ">>>Specified file does not exist!", file = sys.stderr )
        sys.exit( 2 )

    # Get the main dict element as a property list.
    dictProperty = getMainDict( options.queue )
    if dictProperty is None:
        return
    # Get the dict-element.
    for key in dictProperty.keys():
        # if "source" in key or "dest" in key:
        print( "%30s %s" % ( key, dictProperty[key] ) )

# Entry point.
if __name__ == "__main__":
    main( sys.argv )

